import React from 'react'
import PropTypes from 'prop-types'
import { Form, Input, Row,Switch, Col, Button, Icon, Select, Radio, Table, DatePicker, InputNumber, message, Modal as antdModal } from 'antd'
import { connect } from 'dva'
import { routerRedux } from 'dva/router'
import moment from 'moment'
import Modal from './Modal'
import { transactionTypeData, paymentType } from 'utils/seletLocalData'
import styles from '../../../themes/detail.less'
import { ListMenuType } from '../../../utils/enums'
import {getArrtoColums} from '../../../utils/createTransactionCloum';
import { Page, List, DropOption ,WordCard} from "../../../components";
import {converDate} from 'utils'

const FormItem = Form.Item
const ButtonGroup = Button.Group
const Option = Select.Option
const RadioGroup = Radio.Group
const { TextArea } = Input

const confirm = antdModal.confirm

const formItemLayout = {
  labelCol: {
    span: 12,
  },
  wrapperCol: {
    span: 12,
  },
}

const ColProps = {
  span: 8,
  style: {
    marginBottom: 0,
  },
}

const ButtonProps = {
  size: 'large',
  style: {
    marginBottom: 0,
  },
}
const VisibleProps = [
  {
    name: 'ture',
    value: '1',
  },
  {
    name: 'false',
    value: '0',
  },
]
const TransactionReceiptDetail = ({
  transactionReportDetail,
  dispatch,
  loading,
  location,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
  },
}) => {
  const dateFormat = 'DD/MM/YYYY';
  const item = transactionReportDetail.data || {}
  const { customerData, customerId, customerAccount, customerEntity, modalVisible, modalType, fromClients, currentItem, currenciesRateData,selectedRows_from,selectedRows_to } = transactionReportDetail
  const { toClients, customerInfo, companyAccount, CompfirmVisible,currenciesTypeData, detailModalType, serviceAmountData, showCustomerOperation,selectedRowKeys,selectedRowKeys_from,selectedRowKeys_to } = transactionReportDetail
  const modalProps = {
    item: modalType === 'create' ? {} : currentItem,
    visible: modalVisible,
    maskClosable: false,
    width: 500,
    detailModalType: detailModalType,
    CompfirmVisible:CompfirmVisible,
    optionData: { customerEntity, customerAccount, companyAccount },
    confirmLoading: loading.effects['transactionReportDetail/update'],
    title: `${modalType === 'create' ? 'Create' : 'Update'}`,
    wrapClassName: 'vertical-center-modal',
    handleType(e) {
      let data = {}
      switch (e) {
        case 'Person':
          data = {
            entityVisible: false,
            accountVisible: false,
          }
          break
        case 'Account':
          data = {
            entityVisible: false,
            accountVisible: true,
          }
          break
        case 'Entity':
          break
        default:
      }
      dispatch({
        type: 'transactionReportDetail/updateState',
        payload: { ...data },
      })
    },
    onOk () {
      dispatch({
        type: `transactionReportDetail/updateComfirmModal`,
        payload: { CompfirmVisible:true },
      })
    },
    onOkComfirm(data){
      let keyandIndex = {}
      if (detailModalType === 'fromModal') {
        keyandIndex.key = fromClients.length
        keyandIndex.index = fromClients.length
      } else if (detailModalType === 'toModal') {
        keyandIndex.key = toClients.length
        keyandIndex.index = toClients.length
      }
      dispatch({
        type: `transactionReportDetail/updateModal`,
        payload: {
          ...data,
          ...keyandIndex,
        },
      })
    },
    onCancelComfirm(){
      dispatch({
        type: `transactionReportDetail/updateComfirmModal`,
        payload: { CompfirmVisible:false },
      })
    },
    onCancel () {
      dispatch({
        type: 'transactionReportDetail/hideModal',
      })
    },
  }

  //实时汇率列表
  const curRatedata = ['currencyCodeFrom', 'currencyCodeTo', 'buyingBankRate1', 'buyingRate1', 'sellingBankRate1', 'sellingRate1'];
  const Clientdata_from = ['Type/type', 'Payment/payment', 'CompanyAccount/companyAccountId', 'Amount/foreignAmount', 'Comments/fundsComment'];
  const Clientdata_to = ['Type/type', 'Payment/payment', 'CompanyAccount/companyAccountId', 'Amount/foreignAmount', 'Comments/fundsComment'];
  const curRateColumns = getArrtoColums(curRatedata)
  const fromClientColumns = getArrtoColums(Clientdata_from,companyAccount)
  const toClientColumns = getArrtoColums(Clientdata_to,companyAccount)
  const listProps_from = {
    rowSelection: {
      selectedRowKeys:selectedRowKeys_from,
      type:'radio',
      onChange: (keys,selectedRows) => {
        dispatch({
          type: 'transactionReportDetail/updateSelectState',
          payload: {
            selectedRowKeys_from: keys,
            selectedRows_from:selectedRows
          },
        })
      },
    }
  }
  const listProps_from_one = {
    dataSource:selectedRows_from,
    menuType: ListMenuType.MENU_UPDATE,
    location,
    pagination:false,
    columnsData: [
      {
        title: 'Type',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: 'Payment',
        dataIndex: 'payment',
        key: 'payment',
      },
      {
        title: 'CompanyAccount',
        dataIndex: 'companyAccountId',
        key: 'companyAccountId',
      },
      {
        title: 'Amount',
        dataIndex: 'foreignAmount',
        key: 'foreignAmount',
      },
      {
        title: 'Comments',
        dataIndex: 'fundsComment',
        key: 'fundsComment',
      }
    ],
    onEditItem (item) {
      dispatch({
        type:'transactionReportDetail/updateModalState',
        payload:{
          modalType:'update',
          currentItem:item,
          detailModalType:'fromModal'
        }
      })
    },
  }
  const listProps_to = {
    rowSelection: {
      selectedRowKeys: selectedRowKeys_to,
      type:'radio',
      onChange: (keys,selectedRows) => {
        dispatch({
          type: 'transactionReportDetail/updateSelectState',
          payload: {
            selectedRowKeys_to: keys,
            selectedRows_to:selectedRows
          },
        })
      },
    }
  }
  const listProps_to_one={
    dataSource:selectedRows_to,
    menuType: ListMenuType.MENU_UPDATE,
    location,
    pagination:false,
    columnsData: [
      {
        title: 'Type',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: 'Payment',
        dataIndex: 'payment',
        key: 'payment',
      },
      {
        title: 'CustomerAccount',
        dataIndex: 'customerId',
        key: 'customerId',
      },
      {
        title: 'Amount',
        dataIndex: 'foreignAmount',
        key: 'foreignAmount',
      },
      {
        title: 'Comments',
        dataIndex: 'fundsComment',
        key: 'fundsComment',
      }
    ],
    onEditItem (item) {
      dispatch({
        type:'transactionReportDetail/updateModalState',
        payload:{
          modalType:'update',
          currentItem:item,
          detailModalType:'toModal'
        }
      })
    },
  }
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      if (fromClients.length === 0) {
        message.error('At least one \'fromClient\' is needed')
        return
      }
      if (toClients.length === 0) {
        message.error('At least one \'toClient\' is needed')
        return
      }
      let fieldsValue = getFieldsValue()
      if(fieldsValue.birthdate) {
        fieldsValue.birthdate = fieldsValue.birthdate.format('YYYY-MM-DD')
      }
      fieldsValue.dateTransaction = fieldsValue.dateTransaction.format('YYYY-MM-DD')
      const serverData = serviceAmountData.filter(fee => fieldsValue.serviceFee == fee.id)
      fieldsValue.visible= fieldsValue.visible === true?'1':'0';
      const data = {
        ...fieldsValue,
        toClients,
        fromClients,
        amountLocal:200,//暂时写死
        id: item.id||1,
        customer_id:transactionReportDetail.customerId,
        serviceFee: serverData[0],
      }
      dispatch({
        type: 'transactionReportDetail/saveAll',
        payload: data,
      })
      dispatch(routerRedux.push({
        pathname: `/transactionreport/`,
      }))
    })
  }

  const onSearch = () => {
    dispatch(routerRedux.push({
      pathname: `/transactionreceipt`,
    }))
  }

  const onVerify = () => {
    dispatch(routerRedux.push({
      pathname: `/transactionreceipt/preview/verify`,
    }))
  }

  const handleFromType = (e) => {
    dispatch({
      type: 'transactionReportDetail/getCustomerAccount',
      payload: {
        customerId: customerId,
      },
    })
  }

  const handleCustomerSelect = (e) => {
    dispatch({
      type: 'transactionReportDetail/updateState',
      payload: {
        customerId: e,
      },
    })
  }

  const handleCustomerSearch = () => {
    const data = {
      ...getFieldsValue(),
    }
    const { firstName, lastName, phoneNumber } = data
    const searchData = { firstName, lastName, phoneNumber }
    dispatch({
      type: 'transactionReportDetail/getCustomer',
      payload: {
        ...searchData,
      },
    })
  }

  const handleCreateFromDetail = () => {
    dispatch({
      type: 'transactionReportDetail/showModal',
      payload: {
        modalType: 'create',
        currentItem: {},
        detailModalType: 'fromModal',
      },
    })
  }

  const handleCreateToDetail = () => {
    dispatch({
      type: 'transactionReportDetail/showModal',
      payload: {
        modalType: 'create',
        currentItem: {},
        detailModalType: 'toModal',
      },
    })
  }
  const tableStyle = {
    marginBottom: '20px',
  }
  const handleMenuClick = (record, e, list, type) => {
    let theModalType = type.replace(/Clients/, 'Modal')
    if (e.key === '1') {
      dispatch({
        type: 'transactionReportDetail/showModal',
        payload: {
          modalType: 'update',
          currentItem: record,
          detailModalType: theModalType,
        },
      })
    } else if (e.key === '2') {
      confirm({
        title: 'Are you sure delete this record?',
        onOk () {
          // 删除接口
          dispatch({
            type: 'transactionReportDetail/deletelocal',
            payload: {
              currentItem: record,
              arr: list,
              arrname: type,
            },
          })
        },
      })
    }
  }
  const menuData = [{
    key: '1',
    name: 'Update',
  }, {
    key: '2',
    name: 'Delete',
  }, {
    key: '4',
    name: 'Verify',
  }]

  const createMenu = (type, data) => {
    let resArr = []
    for (let i = 0; i < data.length; i++) {
      let s = type & (1 << i)
      if (s != 0) {
        resArr.push(data[i])
      }
    }
    return resArr
  }
  const createColumns = (thecolumns, list, type) => {
    let menulistArr = createMenu(3, menuData)
    let operColumn = {
      title: 'Operation',
      key: 'operation',
      width: 100,
      render: (text, record) => {
        return <DropOption onMenuClick={e => handleMenuClick(record, e, list, type)} menuOptions={menulistArr} />
      },
    }
    thecolumns.push(operColumn)
  }



  /**
   *  @desc  当前FromCurrency、ToCurrency是否都被选中的标志。
   *  @func  均被选中则dispatch获取实时汇率，表格形式展现
   */
  const handleCurrencyChange = (type, value) => {
    const data = {
      ...getFieldsValue(),
    }
    const { fromCurrencyCode, toCurrencyCode } = data//得到值并非最新所以需要判断
    //type是from则判断to的值，type是to则判断from的值
    const checkValue = type == 'from' ? toCurrencyCode : fromCurrencyCode;
    const toValue = type == 'from' ? toCurrencyCode : value;
    const fromValue = type == 'from' ? value : fromCurrencyCode;
    if (checkValue) {
      dispatch({
        type: 'transactionReportDetail/getCurrencyRate',
        payload: {
          currencyCodeFrom: 'NZD',//fromValue,
          currencyCodeTo: 'USD'//toValue,
        },
      })
    }
  }

  const customerOption = customerData.map(d => <Option key={d.id}>{d.customerNumber}</Option>)
  const transactionTypeOption = transactionTypeData.map(d => <Option key={d.value}>{d.value}</Option>)
  const customerAccountOption = customerAccount.map(d => <Option key={d.accountId}>{d.name}</Option>)
  const companyAccountOption = companyAccount.map(d => <Option key={d.companyAccountId}>{d.name}</Option>)
  const currenciesTypeOption = currenciesTypeData.map(d => <Option key={d.code}>{d.code}</Option>)
  const paymentTypeOption = paymentType.map(d => <Option key={d.key}>{d.value}</Option>)
  const serviceAmountOption = serviceAmountData.map(d => <Option key={d.id}>{d.serviceFee}</Option>)
  const VisibleOption = VisibleProps.map(d => <Option key={d.value}>{d.name}</Option>)
  return (
    <Page inner>
      <Form layout="horizontal">
         <Row>
            <Col span={5}>
              <div className={styles.div_buttonGroup}>
                <ButtonGroup {...ButtonProps}>
                  <Button onClick={handleOk}>
                    Save<Icon type="save" />
                  </Button>
                </ButtonGroup>
              </div>
            </Col>
            <Col span={7} offset={12}>
            <WordCard status={item.status} type="status" />
            </Col>
        </Row>
        <div className={styles.div_form}>
          {/* CustomerInfo */}
          <div className={styles.title}>CustomerInfo</div>
          <div className={styles.div_buttonGroup}>
            <ButtonGroup {...ButtonProps}>
              <Button onClick={handleCustomerSearch}>
                Search<Icon type="search" />
              </Button>
              <Button onClick={onSearch}>
                AddCustomer<Icon type="search" />
              </Button>
            </ButtonGroup>
          </div>
          <Row gutter={0}>
            <Col {...ColProps} >
              <FormItem label="FirstName" hasFeedback {...formItemLayout}>
                {getFieldDecorator('firstName', {
                  initialValue: item.firstName,
                })(<Input disabled/>)}
              </FormItem>
            </Col>
            <Col {...ColProps} >
              <FormItem label="LastName" hasFeedback {...formItemLayout}>
                {getFieldDecorator('lastName', {
                  initialValue: item.lastName,
                })(<Input disabled/>)}
              </FormItem>
            </Col>
            <Col {...ColProps} >
              <FormItem label="PhoneNumber" hasFeedback {...formItemLayout}>
                {getFieldDecorator('phoneNumber', {
                  initialValue: item.phoneNumber,
                  rules: [
                    {
                      required: false,
                      max: 8,
                      min: 1,
                    },
                  ],
                })(<Input disabled/>)}
              </FormItem>
            </Col>
            <Col {...ColProps} >
              <FormItem label="CustomerNo" hasFeedback {...formItemLayout}>
                {getFieldDecorator('customerNumber', {
                  initialValue: customerInfo.customerNumber,
                })(<Input disabled />)}
              </FormItem>
            </Col>
            <Col {...ColProps} >
              <FormItem label="MiddleName" hasFeedback {...formItemLayout}>
                {getFieldDecorator('middleName', {
                  initialValue: customerInfo.middleName,
                })(<Input disabled />)}
              </FormItem>
            </Col>
            <Col {...ColProps} >
              <FormItem label="Birthdate" hasFeedback {...formItemLayout}>
                {getFieldDecorator('birthdate', {
                  initialValue: customerInfo.birthdate ? moment(converDate(customerInfo.birthdate),dateFormat) : '',
                })(<DatePicker style={{ width: '100%' }} disabled format={dateFormat}/>)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col {...ColProps} >
              <FormItem label="Gender" hasFeedback {...formItemLayout}>
                {getFieldDecorator('gender', {
                  initialValue: customerInfo.gender,
                })(<Input disabled />)}
              </FormItem>
            </Col>
          </Row>

          {/* TransactionInfo */}
          {showCustomerOperation &&
          <div>
            <div className={styles.title}>TransactionInfo</div>
            <Row gutter={0}>
            <Col {...ColProps} >
                <FormItem label="TransactionNumber" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('transactionNumber', {
                    initialValue: item.transactionNumber,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input disabled/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="TransactionDate" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('dateTransaction', {
                    initialValue: item.dateTransaction ? moment(converDate(item.dateTransaction),dateFormat) : '',
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<DatePicker style={{ width: '100%' }} format={dateFormat}/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="Visible" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('visible', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(
                    <Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross" />}/>
                  )}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="FromCurrencyCode" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('fromCurrencyCode', {
                    initialValue: item.fromCurrencyCode,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} onSelect={handleCurrencyChange.bind(null, 'from')} disabled>{currenciesTypeOption}</Select>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="FromAmount" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('fromAmount', {
                    initialValue: item.fromAmount,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<InputNumber style={{ width: '100%' }} disabled/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="ToCurrencyCode" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('toCurrencyCode', {
                    initialValue: item.toCurrencyCode,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} onSelect={handleCurrencyChange.bind(null, 'to')} disabled>{currenciesTypeOption}</Select>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="ToAmount" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('toAmount', {
                    initialValue: item.toAmount,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<InputNumber style={{ width: '100%' }} disabled/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="ExchangeRate" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('exchangeRate', {
                    initialValue: item.exchangeRate,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<InputNumber style={{ width: '100%' }} disabled/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="TransmodeCode" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('transmodeCode', {
                    initialValue: item.transmodeCode,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} disabled>{currenciesTypeOption}</Select>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="transactionDescription" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('transactionDescription', {
                    initialValue: item.transactionDescription,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<TextArea disabled/>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="TransmodeComm" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('transmodeComment', {
                    initialValue: item.transmodeComment,
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input disabled/>)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="8" offset="16">
                <FormItem label="AmountLocal" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('amountLocal', {
                    initialValue: item.amountLocal,
                    rules: [
                      {
                        required: false,
                      },
                    ],
                  })(<InputNumber style={{ width: '100%' }} disabled/>)}
                </FormItem>
              </Col>
            </Row>
            {/* 选择后显示的实时汇率 如果汇率被选择了则显示该table*/}
            {
              currenciesRateData.length ? <Table dataSource={currenciesRateData} columns={curRateColumns} pagination={false} style={tableStyle} /> : ''
            }
            <div className={styles.title}>FromClient</div>
            <Table columns={fromClientColumns} dataSource={fromClients} pagination={false} style={tableStyle} {...listProps_from}/>
            {
              selectedRowKeys_from.length > 0&&<List {...listProps_from_one}/>
            }
            <div className={styles.title}>toClient</div>
            <Table columns={toClientColumns} dataSource={toClients} pagination={false} style={tableStyle} {...listProps_to}/>
            {
              selectedRowKeys_to.length > 0 &&<List {...listProps_to_one}/>
            }
            <div className={styles.title}>Service Fee</div>
            <Row gutter={0}>
              <Col {...ColProps} >
                <FormItem label="CompanyAccount" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('companyAccountId', {
                    initialValue: item.serviceFee&&item.serviceFee.companyAccountId.toString(),
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} disabled>{companyAccountOption}</Select>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="PaymentType" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('payment', {
                    initialValue: item.serviceFee&&item.serviceFee.payment.toString(),
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} disabled>{paymentTypeOption}</Select>)}
                </FormItem>
              </Col>
              <Col {...ColProps} >
                <FormItem label="ServiceAmount" hasFeedback {...formItemLayout}>
                  {getFieldDecorator('serviceFee', {
                    initialValue: item.serviceFee&&item.serviceFee.amount.toString(),
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Select style={{ width: '100%' }} disabled>{serviceAmountOption}</Select>)}
                </FormItem>
              </Col>
            </Row>
          </div>}
        </div>
      </Form>
      {modalVisible && <Modal {...modalProps} />}
    </Page>
  )
}

TransactionReceiptDetail.propTypes = {
  form: PropTypes.object.isRequired,
  dispatch: PropTypes.func,
  transactionReportDetail: PropTypes.object,
  loading: PropTypes.object,
}

export default connect(({ transactionReportDetail, loading }) => ({ transactionReportDetail, loading }))(Form.create()(TransactionReceiptDetail))
